﻿function Invoke-UTF8RestMethod {
    param(
        [string]$Uri,
        [string]$Method = "POST",
        [object]$Body
    )

    $webClient = New-Object System.Net.WebClient
    $webClient.Headers.Add("Content-Type", "application/json; charset=utf-8")
    $webClient.Encoding = [System.Text.Encoding]::UTF8

    try {
        $jsonBody = $Body | ConvertTo-Json
        $response = $webClient.UploadString($Uri, $Method, $jsonBody)
        return $response | ConvertFrom-Json
    } finally {
        $webClient.Dispose()
    }
}

function Invoke-UTF8RestMethodWithHeaders {
    param(
        [string]$Uri,
        [string]$Method = "POST",
        [object]$Body,
        [hashtable]$Headers = @{}
    )

    $webClient = New-Object System.Net.WebClient
    $webClient.Headers.Add("Content-Type", "application/json; charset=utf-8")
    $webClient.Encoding = [System.Text.Encoding]::UTF8

    # 添加自定义请求头
    foreach ($header in $Headers.GetEnumerator()) {
        $webClient.Headers.Add($header.Key, $header.Value)
    }

    try {
        $jsonBody = $Body | ConvertTo-Json
        $response = $webClient.UploadString($Uri, $Method, $jsonBody)
        return $response | ConvertFrom-Json
    } finally {
        $webClient.Dispose()
    }
}

# 状态显示转换函数
function Get-BookingStatusDisplay {
    param([string]$status)

    $statusMap = @{
        "PENDING"    = "待确认"
        "CONFIRMED"  = "已确认 ✅"
        "CANCELLED"  = "已取消 ❌"
        "CHECKED_IN" = "已值机 🛄"
        "BOARDED"    = "已登机 ✈️"
        "COMPLETED"  = "已完成 🏁"
        "NO_SHOW"    = "未登机 👥"
    }

    if ($statusMap.ContainsKey($status)) {
        return $statusMap[$status]
    } else {
        return "$status (未知状态)"
    }
}


function Show-WelcomeScreen {
    Clear-Host
    Write-Host "==================================================" -ForegroundColor Cyan
    Write-Host "          欢迎使用航空公司预订系统" -ForegroundColor Yellow
    Write-Host "==================================================" -ForegroundColor Cyan
    Write-Host ""
    Write-Host "请选择你要进行的操作：" -ForegroundColor White
    Write-Host ""
    Write-Host "1. 用户注册" -ForegroundColor Green
    Write-Host "2. 用户登录"
    Write-Host "3. 查询航班"
    Write-Host "4. 创建预订"
    Write-Host "5. 查询我的预订"
    Write-Host "6. 取消预订"
    Write-Host "7. 退出系统"
    Write-Host ""
    Write-Host "请输入选项 (1-7): " -ForegroundColor White -NoNewline
}

function Register-User {
    Clear-Host
    Write-Host "=== 用户注册 ===" -ForegroundColor Cyan
    Write-Host ""
    
    # 输入用户名
    Write-Host "请输入用户名：" -NoNewline
    $username = Read-Host
    
    # 输入邮箱
    Write-Host "请输入邮箱：" -NoNewline
    $email = Read-Host
    
    # 输入密码
    Write-Host "请输入密码：" -NoNewline
    $password = Read-Host
    
    Write-Host ""
    Write-Host "正在注册..." -ForegroundColor Yellow
    
    $userBody = @{
        username = $username
        password = $password
        email = $email
    }
    
    try {
        $result = Invoke-UTF8RestMethod -Uri "http://localhost:8080/api/auth/register" -Body $userBody
        
        if ($result.success) {
            Write-Host ""
            Write-Host "注册成功！" -ForegroundColor Green
            Write-Host "用户ID: $($result.data.id)" -ForegroundColor Yellow
            Write-Host "用户名: $($result.data.username)" -ForegroundColor Yellow
            Write-Host "邮箱: $($result.data.email)" -ForegroundColor Yellow
            
            # 保存用户信息
            $global:CurrentUser = $result.data
        } else {
            Write-Host ""
            Write-Host "注册失败: $($result.message)" -ForegroundColor Red
        }
    } catch {
        Write-Host ""
        Write-Host "注册请求失败: $($_.Exception.Message)" -ForegroundColor Red
    }
    
    Write-Host ""
    Write-Host "按任意键返回主菜单..." -NoNewline
    $null = Read-Host
}

function User-Login {
    Clear-Host
    Write-Host "=== 用户登录 ===" -ForegroundColor Cyan
    Write-Host ""
    
    Write-Host "请输入用户名：" -NoNewline
    $username = Read-Host
    
    Write-Host "请输入密码：" -NoNewline
    $password = Read-Host
    
    Write-Host ""
    Write-Host "正在登录..." -ForegroundColor Yellow
    
    $loginBody = @{
        username = $username
        password = $password
    }
    
    try {
        $result = Invoke-UTF8RestMethod -Uri "http://localhost:8080/api/auth/login" -Body $loginBody
        
        if ($result.success) {
            Write-Host ""
            Write-Host "登录成功！" -ForegroundColor Green
            Write-Host "欢迎回来, $($result.data.username)!" -ForegroundColor Yellow
            
            $global:CurrentUser = $result.data
        } else {
            Write-Host ""
            Write-Host "登录失败: $($result.message)" -ForegroundColor Red
        }
    } catch {
        Write-Host ""
        Write-Host "登录请求失败: $($_.Exception.Message)" -ForegroundColor Red
    }
    
    Write-Host ""
    Write-Host "按任意键返回主菜单..." -NoNewline
    $null = Read-Host
}

function Show-Flights {
    Clear-Host
    Write-Host "=== 航班查询 ===" -ForegroundColor Cyan
    Write-Host ""
    
    try {
        $flights = Invoke-RestMethod -Uri "http://localhost:8080/api/flights" -Method GET
        
        if ($flights.success -and $flights.data.Count -gt 0) {
            Write-Host "找到 $($flights.data.Count) 个航班:" -ForegroundColor Green
            Write-Host ""
            
            for ($i = 0; $i -lt $flights.data.Count; $i++) {
                $flight = $flights.data[$i]
                Write-Host "$($i + 1). 航班号: $($flight.flightNumber)" -ForegroundColor White
                Write-Host "   航空公司: $($flight.airline)" -ForegroundColor White
                Write-Host "   航线: $($flight.departureCity) → $($flight.arrivalCity)" -ForegroundColor White
                Write-Host "   出发时间: $($flight.departureTime)" -ForegroundColor White
                Write-Host "   经济舱: ￥$($flight.economyPrice)  商务舱: ￥$($flight.businessPrice)" -ForegroundColor White
                Write-Host ""
            }
        } else {
            Write-Host "暂无航班信息" -ForegroundColor Yellow
        }
    } catch {
        Write-Host "查询航班失败: $($_.Exception.Message)" -ForegroundColor Red
    }
    
    Write-Host ""
    Write-Host "按任意键返回主菜单..." -NoNewline
    $null = Read-Host
}

function Create-Booking {
    Clear-Host
    Write-Host "=== 创建预订 ===" -ForegroundColor Cyan
    Write-Host ""

    if (-not $global:CurrentUser) {
        Write-Host "请先登录！" -ForegroundColor Red
        Write-Host ""
        Write-Host "按任意键返回主菜单..." -NoNewline
        $null = Read-Host
        return
    }

    Write-Host "当前用户: $($global:CurrentUser.username) (ID: $($global:CurrentUser.id))" -ForegroundColor Yellow
    Write-Host ""

    # 显示航班列表
    try {
        $flights = Invoke-RestMethod -Uri "http://localhost:8080/api/flights" -Method GET
        if ($flights.success -and $flights.data.Count -gt 0) {
            Write-Host "可用航班:" -ForegroundColor Green
            for ($i = 0; $i -lt $flights.data.Count; $i++) {
                $flight = $flights.data[$i]
                Write-Host "  $($i + 1). $($flight.flightNumber) | $($flight.departureCity)-$($flight.arrivalCity) | 经济舱:￥$($flight.economyPrice) | 商务舱:￥$($flight.businessPrice)" -ForegroundColor White
            }
            Write-Host ""
        } else {
            Write-Host "暂无可用航班" -ForegroundColor Yellow
            Write-Host ""
            Write-Host "按任意键返回主菜单..." -NoNewline
            $null = Read-Host
            return
        }
    } catch {
        Write-Host "获取航班信息失败" -ForegroundColor Red
        Write-Host ""
        Write-Host "按任意键返回主菜单..." -NoNewline
        $null = Read-Host
        return
    }

    # 输入航班选择
    Write-Host "请选择航班 (1-$($flights.data.Count)): " -NoNewline
    $flightChoice = Read-Host

    if ($flightChoice -match "^\d+$" -and [int]$flightChoice -ge 1 -and [int]$flightChoice -le $flights.data.Count) {
        $selectedFlight = $flights.data[[int]$flightChoice - 1]
        $flightId = $selectedFlight.id
        Write-Host "已选择航班: $($selectedFlight.flightNumber) (ID: $flightId)" -ForegroundColor Green
    } else {
        Write-Host "无效选择！" -ForegroundColor Red
        Write-Host ""
        Write-Host "按任意键返回主菜单..." -NoNewline
        $null = Read-Host
        return
    }

    # 输入乘客信息
    Write-Host "请输入乘客姓名: " -NoNewline
    $passengerName = Read-Host

    Write-Host "请选择座位等级 (1-经济舱, 2-商务舱): " -NoNewline
    $seatChoice = Read-Host
    $seatClass = if ($seatChoice -eq "2") { "BUSINESS" } else { "ECONOMY" }

    Write-Host ""
    Write-Host "正在创建预订..." -ForegroundColor Yellow

    # 创建预订 - 明确传递当前用户ID
    $bookingBody = @{
        userId = $global:CurrentUser.id  # 确保使用当前登录用户的ID
        flightId = $flightId
        passengerName = $passengerName
        seatClass = $seatClass
    }

    Write-Host "请求数据: $($bookingBody | ConvertTo-Json)" -ForegroundColor Gray

    try {
        $result = Invoke-UTF8RestMethod -Uri "http://localhost:8080/api/bookings" -Body $bookingBody

        if ($result.success) {
            Write-Host ""
            Write-Host "预订创建成功！" -ForegroundColor Green
            Write-Host "预订ID: $($result.data.id)" -ForegroundColor Yellow
            Write-Host "乘客: $($result.data.passengerName)" -ForegroundColor Yellow
            Write-Host "航班: $($selectedFlight.flightNumber)" -ForegroundColor Yellow
            Write-Host "座位: $($result.data.seatClass)" -ForegroundColor Yellow
            Write-Host "价格: ￥$($result.data.price)" -ForegroundColor Yellow

            # 立即验证预订是否可查询
            Write-Host ""
            Write-Host "正在验证预订关联..." -ForegroundColor Cyan
            Start-Sleep 2

            # 直接查询刚创建的预订详情，检查用户关联
            try {
                $bookingDetail = Invoke-RestMethod -Uri "http://localhost:8080/api/bookings/$($result.data.id)" -Method GET
                if ($bookingDetail.success) {
                    Write-Host "✅ 预订详情查询成功" -ForegroundColor Green

                    # 检查用户关联
                    if ($bookingDetail.data.user -and $bookingDetail.data.user.id -eq $global:CurrentUser.id) {
                        Write-Host "✅ 预订正确关联到当前用户 (ID: $($global:CurrentUser.id))" -ForegroundColor Green
                    } else {
                        Write-Host "❌ 预订关联的用户ID: $($bookingDetail.data.user.id)" -ForegroundColor Red
                        Write-Host "❌ 当前用户ID: $($global:CurrentUser.id)" -ForegroundColor Red
                        Write-Host "❌ 用户ID不匹配！" -ForegroundColor Red
                    }
                }
            } catch {
                Write-Host "❌ 预订详情查询异常: $($_.Exception.Message)" -ForegroundColor Red
            }
        } else {
            Write-Host ""
            Write-Host "预订创建失败: $($result.message)" -ForegroundColor Red
        }
    } catch {
        Write-Host ""
        Write-Host "创建预订请求失败: $($_.Exception.Message)" -ForegroundColor Red
    }

    Write-Host ""
    Write-Host "按任意键返回主菜单..." -NoNewline
    $null = Read-Host
}

function Show-MyBookings {
    Clear-Host
    Write-Host "=== 我的预订 ===" -ForegroundColor Cyan
    Write-Host ""
    
    if (-not $global:CurrentUser) {
        Write-Host "请先登录！" -ForegroundColor Red
        Write-Host ""
        Write-Host "按任意键返回主菜单..." -NoNewline
        $null = Read-Host
        return
    }
    
    Write-Host "当前用户: $($global:CurrentUser.username) (ID: $($global:CurrentUser.id))" -ForegroundColor Yellow
    Write-Host ""

    Write-Host "正在查询您的预订..." -ForegroundColor Yellow

    # 方法1: 使用用户预订API
    try {
        Write-Host "尝试端点: /api/bookings/user/$($global:CurrentUser.id)" -ForegroundColor Gray
        $userBookings = Invoke-RestMethod -Uri "http://localhost:8080/api/bookings/user/$($global:CurrentUser.id)" -Method GET

        if ($userBookings.success) {
            if ($userBookings.data.Count -gt 0) {
                Write-Host "✅ 您有 $($userBookings.data.Count) 个预订:" -ForegroundColor Green
                Write-Host ""

                foreach ($booking in $userBookings.data) {
                    Write-Host "预订ID: $($booking.id)" -ForegroundColor White
                    Write-Host "乘客: $($booking.passengerName)" -ForegroundColor White
                    Write-Host "航班: $($booking.flight.flightNumber)" -ForegroundColor White
                    Write-Host "航线: $($booking.flight.departureCity) → $($booking.flight.arrivalCity)" -ForegroundColor White
                    Write-Host "座位: $($booking.seatClass)" -ForegroundColor White
                    Write-Host "价格: ￥$($booking.price)" -ForegroundColor White
                    $statusDisplay = Get-BookingStatusDisplay -status $booking.status
                    Write-Host "状态: $statusDisplay" -ForegroundColor White
                    Write-Host "------------------------------------" -ForegroundColor Gray
                    Write-Host ""
                }
            } else {
                Write-Host "ℹ️ 通过用户预订API查询成功，但没有找到您的预订" -ForegroundColor Yellow
            }
        } else {
            Write-Host "❌ 用户预订API返回失败: $($userBookings.message)" -ForegroundColor Red
        }
    } catch {
        Write-Host "❌ 用户预订API查询异常: $($_.Exception.Message)" -ForegroundColor Red

        # 备选方案：查询所有预订然后过滤
        Write-Host "正在尝试备选查询方式..." -ForegroundColor Yellow
        try {
            $allBookings = Invoke-RestMethod -Uri "http://localhost:8080/api/bookings" -Method GET
            if ($allBookings.success) {
                $myBookings = $allBookings.data | Where-Object {
                    $_.user -and $_.user.id -eq $global:CurrentUser.id
                }
                if ($myBookings.Count -gt 0) {
                    Write-Host "✅ 通过过滤找到 $($myBookings.Count) 个您的预订:" -ForegroundColor Green
                    foreach ($booking in $myBookings) {
                        Write-Host "  - 预订ID: $($booking.id) | 乘客: $($booking.passengerName) | 航班: $($booking.flight.flightNumber) | $($booking.seatClass) | ￥$($booking.price)" -ForegroundColor White
                    }
                } else {
                    Write-Host "ℹ️ 确实没有找到您的预订" -ForegroundColor Yellow
                }
            }
        } catch {
            Write-Host "❌ 备选查询方式失败: $($_.Exception.Message)" -ForegroundColor Red
        }
    }

    Write-Host ""
    Write-Host "按任意键返回主菜单..." -NoNewline
    $null = Read-Host
}

function Cancel-Booking {
    Clear-Host
    Write-Host "=== 取消预订 ===" -ForegroundColor Cyan
    Write-Host ""
    
    if (-not $global:CurrentUser) {
        Write-Host "请先登录！" -ForegroundColor Red
        Write-Host ""
        Write-Host "按任意键返回主菜单..." -NoNewline
        $null = Read-Host
        return
    }
    
    Write-Host "当前用户: $($global:CurrentUser.username) (ID: $($global:CurrentUser.id))" -ForegroundColor Yellow
    Write-Host ""

    Write-Host "请输入要取消的预订ID: " -NoNewline
    $bookingId = Read-Host

    Write-Host ""
    Write-Host "正在查询预订 $bookingId 的当前状态..." -ForegroundColor Yellow

    # 1. 先查询当前状态
    try {
        $currentBooking = Invoke-RestMethod -Uri "http://localhost:8080/api/bookings/$bookingId" -Method GET
        if ($currentBooking.success) {
            Write-Host "✅ 当前预订状态: $($currentBooking.data.status)" -ForegroundColor Cyan
            Write-Host "   乘客: $($currentBooking.data.passengerName)" -ForegroundColor Cyan
            Write-Host "   航班: $($currentBooking.data.flight.flightNumber)" -ForegroundColor Cyan
        }
    } catch {
        Write-Host "❌ 查询预订失败: $($_.Exception.Message)" -ForegroundColor Red
    }

    Write-Host ""
    Write-Host "正在尝试取消预订..." -ForegroundColor Yellow

    # 2. 使用支持请求头的函数进行取消
    try {
        $cancelBody = @{ status = "CANCELLED" }
        $headers = @{ "User-Id" = $global:CurrentUser.id }  # 关键：添加用户ID请求头

        Write-Host "发送请求头: User-Id = $($global:CurrentUser.id)" -ForegroundColor Gray

        $result = Invoke-UTF8RestMethodWithHeaders -Uri "http://localhost:8080/api/bookings/$bookingId/status" -Method "PUT" -Body $cancelBody -Headers $headers

        Write-Host "响应数据: $($result | ConvertTo-Json -Depth 3)" -ForegroundColor Gray

        if ($result.success) {
            Write-Host ""
            Write-Host "✅ 预订取消成功！" -ForegroundColor Green
            Write-Host "   更新后的状态: $($result.data.status)" -ForegroundColor Yellow
        } else {
            Write-Host ""
            Write-Host "❌ 取消预订失败: $($result.message)" -ForegroundColor Red
        }
    } catch {
        Write-Host ""
        Write-Host "❌ 取消预订请求失败: $($_.Exception.Message)" -ForegroundColor Red
    }

    Write-Host ""
    Write-Host "按任意键返回主菜单..." -NoNewline
    $null = Read-Host
}

# 主程序循环
function Start-AirlineCLI {
    # 初始化全局变量
    $global:CurrentUser = $null
    
    do {
        Show-WelcomeScreen
        $choice = Read-Host
        
        switch ($choice) {
            "1" { Register-User }
            "2" { User-Login }
            "3" { Show-Flights }
            "4" { Create-Booking }
            "5" { Show-MyBookings }
            "6" { Cancel-Booking }
            "7" { 
                Clear-Host
                Write-Host "感谢使用航空公司预订系统！" -ForegroundColor Green
                Write-Host "再见！" -ForegroundColor Yellow
                Write-Host ""
                return 
            }
            default { 
                Write-Host ""
                Write-Host "无效选择，请重新输入！" -ForegroundColor Red
                Start-Sleep 2
            }
        }
    } while ($true)
}

# 启动系统
Clear-Host
Write-Host "正在启动航空公司预订系统..." -ForegroundColor Cyan
Start-Sleep 1
Start-AirlineCLI